import ArticleItem from '@/components/ArticleItem'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import { useLocation } from 'react-router'
import { getSearchResult ,clearSearchResult} from '@/store/action/search'
import { useDispatch  } from 'react-redux'
import { useAppSelector } from '@/store'
import { InfiniteScroll } from 'antd-mobile'
import { useRef, useState ,useEffect} from 'react'
export default function SearchResult() {
  const { search } = useLocation()
  const searchParams = new URLSearchParams(search)
  // 获取 URL 的查询参数 q 的值
  const q = searchParams.get('q') || ''
  console.log('获取查询参数q的值', q)
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(clearSearchResult())
  }, [q, dispatch])
  //  是否还有更多内容
   const [hasMore, setHasMore] = useState(true)
   // 页码
   const page = useRef(0)
   // 加载更多的回调函数
   const loadMoreFn = async () => {
     // 页码加 1
     page.current = page.current + 1
     // 根据新的页码发送请求
     try {
      // 根据新的页码发送请求
      await dispatch(getSearchResult({ q: q, page: page.current, per_page: 10 }))
    } catch (error) {
      console.log(11111111111, error)
      // 没有分页数据需要更新状态，防止重复发送请求的死循环
      setHasMore(false)
    }
   }
  const { results } = useAppSelector((state) => state.search)
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>
      <div className='article-list'>
      {results.map((item) => (
          <ArticleItem key={item.art_id} article={item} />
        ))}
         <InfiniteScroll hasMore={hasMore} loadMore={loadMoreFn} />
      </div>
    </div>
  )
}